//账户管理
'use strict';
import React,{Component} from 'react';
import Header from '../common/header';
import styles from '../style/styles';
import Icon from 'react-native-vector-icons';
import UserSetting from './userSetting';
import GetCode from './getCode';//修改密码 获取手机验证码
import DateTimePicker from 'react-native-modal-datetime-picker';
import MyStroage from '../common/myStroage';
import ImagePicker from 'react-native-image-picker';
import * as URLConstant from '../constant/URLconstant'
import Util from '../common/util'
import Toast from '../common/ToastUtil'
import AddressAdmin from '../address/addressAdmin';

import {
    View,
    Text,
    ScrollView,
    Image,
    TouchableOpacity,
    Platform
} from 'react-native';
export default class userManager extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.successCallback = this.successCallback.bind(this);
        this.errorcallback = this.errorcallback.bind(this);
        this.postPhoto = this.postPhoto.bind(this)
        this.Refresh=this.Refresh.bind(this)
        this.postdate=this.postdate.bind(this)
        this.state = {
            isShowDateTimePicker: false,
            uesr_id: this.props.user_id,
            loaded: true
        };

    }

    componentDidMount() {
        this.getUserManager()

    }

    getUserManager() {
        let user_id = this.state.uesr_id;
        let datakey = [];
        datakey['user_id'] = user_id
        let MESSAGE_URL = URLConstant.USERINFO_URL;
        Util.get(MESSAGE_URL, datakey, this.successCallback, this.errorcallback);
    }

    successCallback(datas) {
        let that = this;
        //LOG(datas)
        let data = datas.data;
        let user_info = data.userInfo
        that.setState({
            loaded: false,
            user_info: user_info
        })
    }

    errorcallback(err) {
        LOG('errorcallback==' + err);
    }


    _showDateTimePicker() {
        this.setState({
            isShowDateTimePicker: true
        })
    }

    _hideDateTimePicker = () => this.setState({isShowDateTimePicker: false})


    _handleDatePicked = (date) => {
        LOG('A date has been picked: ', date)
        this.setState({
            year: date.getUTCFullYear(),
            mouth: date.getMonth() + 1,
            day: date.getDate(),
        })

        this._hideDateTimePicker()

        this.postDate()
    }

    postDate(){
        let user_id=this.state.uesr_id
        let year=this.state.year;
        let mouth=this.state.mouth;
        let day=this.state.day;
        let date = year + '-' + mouth + '-' + day;
        let datakey=[];
        datakey['birthday']=date;
        datakey['user_id']=user_id;
        let url = URLConstant.UPDATAINFOMATION_URL;
        Util.post(url, datakey, this.postdate, this.errorcallback)
    }

    postdate(datas){
        //LOG(datas)
        if (datas.status == 0) {
            Toast.show(datas.msg)
            this.getUserManager()
        }else {
            Toast.show(datas.msg)
        }
    }


    userSetting(type, title) {
        let that = this;
        let user_id=this.state.uesr_id
        //type=  1:昵称  2:性别
        that.props.navigator.push({
            component: UserSetting,
            passProps: {
                type: type,
                title: title,
                user_id:user_id,
                Refresh:this.Refresh,
                navigator:this.props.navigator
            }
        })
    }

    Refresh(){
        this.getUserManager()
    }


    userAddress() {
        let that = this;
        that.props.navigator.push({
            component: AddressAdmin,
        })
    }

    getCode(title, type) {
        let that = this;
        that.props.navigator.push({
            component: GetCode,
            passProps: {
                title: title,
                type: type,
            }
        })
    }

    getImageNameByIOS(imageUri) {
        if (imageUri != "") {
            var names = imageUri.split("/");
            return names[names.length - 1];
        }
    }

    //更改头像
    imagePicker() {
        let that = this;

        const options = {
            title: '选择一张图片',
            cancelButtonTitle: '取消',
            takePhotoButtonTitle: '拍照',
            chooseFromLibraryButtonTitle: '从相册中选择',
            quality: 1.0,
            maxWidth: 500,
            maxHeight: 500,
            storageOptions: {
                skipBackup: true
            }
        };
        ImagePicker.showImagePicker(options, (response)=> {
            if (response.didCancel) {

            }
            else if (response.error) {

            }
            else if (response.customButton) {
            }
            else {
                let source;
                let imageName;
                let imagePath;

                if (Platform.OS === 'android') {
                    source = response.uri;
                    imagePath = response.path;
                    imageName = response.fileName;

                } else {
                    //{"uri":"/var/mobile/Containers/Data/Application/CC01D123-59FA-4205-8B27-C3181596AA5C/Documents/6131CE7A-FD8C-44DB-B9B9-82C322294B88.jpg","isStatic":true}
                    //file:///Users/dev/Library/Developer/CoreSimulator/Devices/DA8C975D-D476-462B-B387-D43FBC55C333/data/Containers/Data/Application/6231A942-22AA-40DC-A303-898EDE2C7533/Documents/2E98BCB0-8A9E-43FF-88E6-E7BE2094EE62.jpg
                    source = response.uri.replace('file://', '');
                    imagePath = response.uri.replace('file://', '');
                    imageName = that.getImageNameByIOS(response.uri);
                }

                let imageinfo = [];
                imageinfo['uri'] = source;//这个是给React-native Image组件显示图片用得地址;
                imageinfo['imageName'] = imageName;//图片名称
                imageinfo['imagePath'] = imagePath;//图片在本机的路径.
                that.setState({
                    default_image: imageinfo,
                });
                this.goUpdataPhoto()
            }
        })
    }

    goUpdataPhoto() {
        let that = this;
        let user_id = this.state.uesr_id
        let das = new FormData();
        let default_image = {
            uri: that.state.default_image['uri'],
            type: "multipart/form-data",
            name: that.state.default_image['imageName']
        };

        das.append("portrait", default_image);
        das.append("user_id", user_id);
        das.append("signme", 1);
        das.append("local", ISLOCAL);
        let url = URLConstant.UPDATAINFOMATION_URL;
        //LOG('posturl==='+url)
        Util.post2(url, das, this.postPhoto, this.errorcallback)
    }


    postPhoto(datas) {
        LOG(datas)
        if (datas.status == 0) {
            Toast.show(datas.msg)
            this.getUserManager()
        }else {
            Toast.show(datas.msg)
        }
    }


    render() {
        let that = this;
        let user_info = this.state.user_info;
        return (
            <View style={{flex:1}}>
                <Header navigator={this.props.navigator} initObj={{ title: '账户管理',id:2}}/>
                {this.state.loaded ?
                    <View style={{flex:1}}>
                        {Util.loading()}
                    </View>
                    :
                    <View style={{flex:1,backgroundColor:"#f0f0f0"}}>
                        <TouchableOpacity style={styles.head_logo_wrap} onPress={()=>this.imagePicker()}>
                            {user_info.portrait == '' ?
                                <View style={styles.user_logo}>
                                    <Image
                                        resizeMode="cover"
                                        style={styles.user_logo1}
                                        source={require('../imgs/user.png')}/>
                                </View>
                                :
                                <View style={styles.user_logo}>
                                    <Image
                                        resizeMode="cover"
                                        style={styles.user_logo1}
                                        source={{uri:user_info.portrait}}/>
                                </View>
                            }
                        </TouchableOpacity>
                        <View style={styles.user_info_setting}>
                            <View style={styles.setting_list}>
                                <Text>用户名</Text>
                                <View style={styles.setting_list_r}>
                                    <Text style={styles.setting_txt}>{user_info.phone_mob}</Text>
                                </View>
                            </View>
                            <TouchableOpacity style={styles.setting_list} onPress={()=>this.userSetting(1,'昵称')}>
                                <Text>昵称</Text>
                                <View style={styles.setting_list_r}>
                                    <Text style={styles.setting_txt}>{user_info.real_name}</Text>
                                    <Icon name={'ios-arrow-forward-outline'} size={20} color={'#999'}/>
                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.setting_list} onPress={()=>this.userSetting(2,'性别')}>
                                <Text>性别</Text>
                                <View style={styles.setting_list_r}>
                                    {user_info.gender == 1 ?
                                        <Text style={styles.setting_txt}>男</Text>
                                        :
                                        <View>
                                            {user_info.gender == 2 ?
                                                <Text style={styles.setting_txt}>女</Text>
                                                :
                                                null}
                                        </View>
                                    }

                                    <Icon name={'ios-arrow-forward-outline'} size={20} color={'#999'}/>
                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.setting_list} onPress={()=>that._showDateTimePicker()}>
                                <Text>出生日期</Text>
                                <View style={styles.setting_list_r}>
                                    <Text style={styles.setting_txt}>{user_info.birthday}</Text>
                                    <Icon name={'ios-arrow-forward-outline'} size={20} color={'#999'}/>
                                </View>
                            </TouchableOpacity>
                            <DateTimePicker
                                visible={this.state.isShowDateTimePicker}
                                onConfirm={this._handleDatePicked}
                                onCancel={this._hideDateTimePicker}
                                titleIOS="请选择你的出生日期"
                                cancelTextIOS='取消'
                                confirmTextIOS='确定'
                                date={new Date()}
                            />
                        </View>
                        <View style={styles.user_info_setting}>
                            <TouchableOpacity style={styles.setting_list} onPress={()=>this.userAddress()}>
                                <Text>地址管理</Text>
                                <View style={styles.setting_list_r}>
                                    <Icon name={'ios-arrow-forward-outline'} size={20} color={'#999'}/>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={styles.user_info_setting}>
                            <TouchableOpacity style={styles.setting_list} onPress={()=>this.getCode('修改密码',2)}>
                                <Text>账户安全</Text>
                                <View style={styles.setting_list_r}>
                                    <Text style={styles.setting_txt}>可修改密码</Text>
                                    <Icon name={'ios-arrow-forward-outline'} size={20} color={'#999'}/>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                }

            </View>
        )
    }
}